<template>
  <div class="profile-container">
    <!-- 页面标题 -->
    <div class="page-title">个人中心</div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 左侧：个人信息 -->
      <div class="content-left">
        <el-card shadow="hover" class="profile-card">
          <div class="profile-header">
            <div class="avatar-container">
              <el-avatar :size="100" class="avatar">
                <img
                    :src="userInfo.headPic || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"
                    :alt="userInfo.nickname || '用户头像'"
                />
              </el-avatar>
              <label class="avatar-upload">
                <el-icon class="upload-icon"><Upload /></el-icon>
                <input type="file" accept="image/*" @change="handleAvatarUpload" />
              </label>
            </div>
            <div class="user-info">
              <h2 class="nickname">{{ userInfo.nickname }}</h2>
              <!-- 显示用户详细信息 -->
              <p class="user-detail">用户ID: {{ userInfo.id ||'1'}}</p>
              <p class="user-detail">用户名: {{ userInfo.userName ||'admin'}}</p>
              <p class="user-detail">邮箱: {{ userInfo.email ||'admin@example.com'}}</p>
              <p class="user-detail">电话: {{ userInfo.phone ||'138'}}</p>
              <p class="user-detail">性别: {{ userInfo.gender === '1' ? '男' : userInfo.gender === '0' ? '女' : '男' }}</p>
              <p class="user-detail">生日: {{ userInfo.birthday ? formatDate(userInfo.birthday) : '' ||'1990-01-15'}}</p>
              <p class="user-detail">个人简介: {{ userInfo.bio || '未填写' }}</p>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧：内容区 -->
      <div class="content-right">
        <!-- 学习路径（分页查询表） -->
        <el-card shadow="hover" class="learning-path-card">
          <div slot="header" class="card-header-flex">
            <span class="card-title">学习路径</span>
            <el-button type="primary" size="small" @click="handleAddPath">
              新增
            </el-button>
          </div>

          <!-- 查询条件 -->
          <el-form :inline="true" :model="pathCondition" class="demo-form-inline" style="margin-bottom: 15px;">
            <el-form-item label="路径名称：">
              <el-input v-model="pathCondition.name" placeholder="请输入名称" clearable />
            </el-form-item>
            <!-- 移除了难度查询条件 -->
            <!-- 移除了用户ID查询条件 -->
            <el-form-item label="是否推荐：">
              <el-select v-model="pathCondition.is_recommended" placeholder="请选择" clearable>
                <el-option label="推荐" value="1" />
                <el-option label="不推荐" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchPath()">查询</el-button>
              <el-button @click="resetPathSearch()" style="margin-left: 10px;">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 学习路径表格 -->
          <el-table :data="pathTableData" style="width: 100%" border stripe size="small">
            <el-table-column prop="id" label="路径ID" width="80" />
            <el-table-column prop="name" label="路径名称" />
            <el-table-column prop="difficulty" label="难度" width="100" />
            <el-table-column prop="days" label="总天数" width="80" />
            <el-table-column prop="user_id" label="用户ID" width="100" />
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="is_recommended" label="是否推荐" width="100">
              <template #default="scope">
                {{ scope.row.is_recommended === 1 ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="160" />
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="handlePathView(scope.row)">
                  查看
                </el-button>
                <el-button size="small" type="primary" @click="handlePathEdit(scope.row)">
                  编辑
                </el-button>
                <el-popconfirm title="您确定要删除吗?" @confirm="handlePathRemove(scope.row.id)">
                  <template #reference>
                    <el-button size="small" type="warning">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页控件 -->
          <div class="demo-pagination-block" style="margin-top: 15px; text-align: right;">
            <el-pagination
                v-model:current-page="pathCurrentPage"
                v-model:page-size="pathPageSize"
                :page-sizes="[6, 7, 8, 9]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pathTotal"
                @size-change="handlePathSizeChange"
                @current-change="handlePathCurrentChange"
            />
          </div>
        </el-card>

        <!-- 工具列表 -->
        <el-card shadow="hover" class="tools-card" style="margin-top: 20px;">
          <div slot="header" class="card-header-flex">
            <span class="card-title">工具列表</span>
            <el-button type="primary" size="small" @click="handleAddTool">
              <el-icon><List /></el-icon> 新增工具
            </el-button>
          </div>

          <!-- 查询条件 -->
          <el-form :inline="true" :model="toolCondition" class="demo-form-inline" style="margin-bottom: 15px;">
            <el-form-item label="工具名称：">
              <el-input v-model="toolCondition.name" placeholder="请输入名称" clearable />
            </el-form-item>
            <el-form-item label="工具类型：">
              <el-input v-model="toolCondition.type" placeholder="请输入类型" clearable />
            </el-form-item>
            <el-form-item label="状态：">
              <el-select v-model="toolCondition.status" placeholder="请选择状态" clearable>
                <el-option label="启用" value="active" />
                <el-option label="禁用" value="inactive" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchTool()">查询</el-button>
              <el-button @click="resetToolSearch()" style="margin-left: 10px;">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 工具表格 -->
          <el-table :data="toolTableData" style="width: 100%" border stripe size="small">
            <el-table-column prop="id" label="工具ID" width="80" />
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="type" label="类型" width="120" />
            <el-table-column prop="free" label="是否免费" width="100">
              <template #default="scope">
                {{ scope.row.free === 1 ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" width="100" />
            <el-table-column prop="usage_count" label="使用次数" width="100" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
                  {{ scope.row.status === 'active' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="160" />
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="handleToolView(scope.row)">
                  查看
                </el-button>
                <el-button size="small" type="primary" @click="handleToolEdit(scope.row)">
                  编辑
                </el-button>
                <el-popconfirm title="您确定要删除吗?" @confirm="handleToolRemove(scope.row.id)">
                  <template #reference>
                    <el-button size="small" type="warning">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页控件 -->
          <div class="demo-pagination-block" style="margin-top: 15px; text-align: right;">
            <el-pagination
                v-model:current-page="toolCurrentPage"
                v-model:page-size="toolPageSize"
                :page-sizes="[6, 7, 8, 9]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="toolTotal"
                @size-change="handleToolSizeChange"
                @current-change="handleToolCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 学习路径查看对话框 -->
    <el-dialog v-model="pathViewDialogVisible" title="路径详情" width="50%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="路径ID">{{ currentPath.id }}</el-descriptions-item>
        <el-descriptions-item label="路径名称">{{ currentPath.name }}</el-descriptions-item>
        <el-descriptions-item label="路径描述">{{ currentPath.description }}</el-descriptions-item>
        <el-descriptions-item label="难度">{{ currentPath.difficulty }}</el-descriptions-item>
        <el-descriptions-item label="总天数">{{ currentPath.days }}</el-descriptions-item>
        <el-descriptions-item label="包含任务">{{ currentPath.tasks }}</el-descriptions-item>
        <el-descriptions-item label="缩略图">
          <img v-if="currentPath.thumbnail_url" :src="currentPath.thumbnail_url" style="max-width: 200px" alt="路径缩略图" />
          <span v-else>无图片</span>
        </el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentPath.user_id }}</el-descriptions-item>
        <el-descriptions-item label="排序">{{ currentPath.sort }}</el-descriptions-item>
        <el-descriptions-item label="是否推荐">{{ currentPath.is_recommended === 1 ? '推荐' : '不推荐' }}</el-descriptions-item>
        <el-descriptions-item label="用户笔记">{{ currentPath.user_note }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentPath.created_at }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ currentPath.updated_at }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 学习路径编辑对话框 -->
    <el-dialog v-model="pathEditDialogVisible" :title="pathEditDialogTitle" width="50%">
      <el-form :model="currentPath" label-width="80px" :rules="pathFormRules" ref="pathFormRef">
        <el-form-item label="路径ID">
          <el-input v-model="currentPath.id" disabled />
        </el-form-item>
        <el-form-item label="路径名称" prop="name">
          <el-input v-model="currentPath.name" />
        </el-form-item>
        <el-form-item label="路径描述">
          <el-input v-model="currentPath.description" type="textarea" />
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-input v-model="currentPath.difficulty" />
        </el-form-item>
        <el-form-item label="总天数" prop="days">
          <el-input v-model="currentPath.days" type="number" min="1" />
        </el-form-item>
        <el-form-item label="包含任务">
          <el-input v-model="currentPath.tasks" type="textarea" />
        </el-form-item>
        <el-form-item label="缩略图URL">
          <el-input v-model="currentPath.thumbnail_url" />
        </el-form-item>
        <el-form-item label="用户ID" prop="user_id">
          <el-input v-model="currentPath.user_id" type="number" min="0" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="currentPath.sort" type="number" />
        </el-form-item>
        <el-form-item label="是否推荐">
          <el-select v-model="currentPath.is_recommended" placeholder="请选择">
            <el-option label="推荐" value="1" />
            <el-option label="不推荐" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户笔记">
          <el-input v-model="currentPath.user_note" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pathEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePathSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 工具查看对话框 -->
    <el-dialog v-model="toolViewDialogVisible" title="工具详情" width="50%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="工具ID">{{ currentTool.id }}</el-descriptions-item>
        <el-descriptions-item label="名称">{{ currentTool.name }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{ currentTool.type }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{ currentTool.description }}</el-descriptions-item>
        <el-descriptions-item label="是否免费">{{ currentTool.free === 1 ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="价格">{{ currentTool.price }}</el-descriptions-item>
        <el-descriptions-item label="使用次数">{{ currentTool.usage_count }}</el-descriptions-item>
        <el-descriptions-item label="缩略图">
          <img v-if="currentTool.thumbnail_url" :src="currentTool.thumbnail_url" style="max-width: 200px" alt="工具缩略图" />
          <span v-else>无图片</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentTool.created_at }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ currentTool.updated_at }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ currentTool.status === 'active' ? '启用' : '禁用' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 工具编辑对话框 -->
    <el-dialog v-model="toolEditDialogVisible" :title="toolEditDialogTitle" width="50%">
      <el-form :model="currentTool" label-width="80px" :rules="toolFormRules" ref="toolFormRef">
        <el-form-item label="工具ID">
          <el-input v-model="currentTool.id" disabled />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="currentTool.name" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-input v-model="currentTool.type" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="currentTool.description" type="textarea" />
        </el-form-item>
        <el-form-item label="是否免费">
          <el-select v-model="currentTool.free" placeholder="请选择">
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="currentTool.price" type="number" min="0" />
        </el-form-item>
        <el-form-item label="缩略图URL">
          <el-input v-model="currentTool.thumbnail_url" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="currentTool.status" placeholder="请选择">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="toolEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleToolSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, Clock, List } from '@element-plus/icons-vue'
import axiosObject from "@/main.js";

// 获取组件实例
const { proxy } = getCurrentInstance()

// 个人信息相关
const userInfo = ref({})

// 学习路径相关状态
const pathTableData = ref([])
const pathViewDialogVisible = ref(false)
const pathEditDialogTitle = ref("")
const pathEditDialogVisible = ref(false)
const currentPath = ref({})
const pathFormRef = ref(null)

// 学习路径查询条件
const pathCondition = ref({ "name": "", "is_recommended": "" })

// 学习路径分页参数
const pathCurrentPage = ref(1)
const pathPageSize = ref(8)
const pathTotal = ref(0)

// 学习路径表单验证规则
const pathFormRules = ref({
  name: [
    { required: true, message: '请输入路径名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  difficulty: [
    { required: true, message: '请输入难度', trigger: 'blur' }
  ],
  days: [
    { required: true, message: '请输入总天数', trigger: 'blur' },
    { type: 'number', min: 1, message: '总天数必须大于0', trigger: 'blur' }
  ],
  user_id: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { type: 'number', min: 0, message: '用户ID必须为非负整数', trigger: 'blur' }
  ]
})

// 工具列表相关状态
const toolTableData = ref([])
const toolViewDialogVisible = ref(false)
const toolEditDialogTitle = ref("")
const toolEditDialogVisible = ref(false)
const currentTool = ref({})
const toolFormRef = ref(null)

// 工具查询条件
const toolCondition = ref({ "name": "", "type": "", "status": "" })

// 工具分页参数
const toolCurrentPage = ref(1)
const toolPageSize = ref(10)
const toolTotal = ref(0)

// 工具表单验证规则
const toolFormRules = ref({
  name: [
    { required: true, message: '请输入工具名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请输入工具类型', trigger: 'blur' }
  ],
  price: [
    {type: 'number', message: '请输入有效的价格', trigger: 'blur'},
    {min: 0, message: '价格不能为负数', trigger: 'blur'}
  ]
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 获取用户信息 - 修改为通过用户ID查询
const fetchUserInfo = async () => {
  try {
    // 从localStorage获取登录用户ID
    const userId = localStorage.getItem('userId')
    if (!userId) {
      // ElMessage.warning('未获取到用户信息，请重新登录')
      return
    }

    // 调用根据ID查询用户的接口
    const response = await axiosObject.get(`/user/getById`)
    if (response.data.code === 200) {
      userInfo.value = response.data.resultData
    } else {
      ElMessage.error(response.data.msg || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 获取用户统计数据
const userStats = ref({})
const fetchUserStats = async () => {
  try {
    const response = await axiosObject.get('/user/stats')
    if (response.data.code === 200) {
      userStats.value = response.data.resultData
    }
  } catch (error) {
    console.error('获取用户统计数据失败:', error)
  }
}

// 上传头像 - 修改接口路径与后端匹配
const handleAvatarUpload = async (e) => {
  const file = e.target.files[0]
  if (!file) return

  const formData = new FormData()
  formData.append('file', file) // 后端参数名为file

  try {
    const response = await axiosObject.post('/user/uploadAvatar', formData, {
      headers: {'Content-Type': 'multipart/form-data'}
    })
    if (response.data.code === 200) {
      ElMessage.success('头像上传成功')
      // 上传成功后更新头像URL到用户信息
      const userId = localStorage.getItem('userId')
      await axiosObject.post('/user/updateAvatar', {
        userId: userId,
        avatarUrl: response.data.resultData.avatarUrl
      })
      // 重新获取用户信息刷新头像
      await fetchUserInfo()
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('上传失败，请重试')
  } finally {
    // 重置input值，允许重复选择同一文件
    e.target.value = ''
  }
}

// 学习路径相关方法
const findPathList = async () => {
  const payload = {
    ...pathCondition.value,
    page: pathCurrentPage.value,
    size: pathPageSize.value
  };

  try {
    const result = await axiosObject.post('/learningPath/list', payload);
    if (result.data.code === 200) {
      pathTableData.value = result.data.resultData.list || [];
      pathTotal.value = result.data.resultData.total || 0;
    } else {
      ElMessage.error('获取学习路径列表失败: ' + (result.data.msg || '未知错误'))
    }
  } catch (error) {
    console.error("获取学习路径列表失败:", error);
    ElMessage.error('网络错误，无法获取学习路径列表')
    pathTableData.value = [];
    pathTotal.value = 0;
  }
};

// 学习路径分页处理
const handlePathCurrentChange = (page) => {
  pathCurrentPage.value = page;
  findPathList();
}

const handlePathSizeChange = (size) => {
  pathPageSize.value = size;
  pathCurrentPage.value = 1;
  findPathList();
}

// 学习路径条件查询
const searchPath = () => {
  pathCurrentPage.value = 1;
  findPathList();
}

// 重置学习路径查询条件
const resetPathSearch = () => {
  pathCondition.value = {"name": "", "is_recommended": ""};
  pathCurrentPage.value = 1;
  findPathList();
}

// 学习路径操作方法
const handlePathView = (row) => {
  currentPath.value = {...row}
  pathViewDialogVisible.value = true
}

const handlePathEdit = (row) => {
  pathEditDialogTitle.value = "编辑学习路径";
  currentPath.value = {...row}
  pathEditDialogVisible.value = true
}

const handleAddPath = () => {
  pathEditDialogTitle.value = "添加学习路径";
  currentPath.value = {
    days: 1,
    sort: 0,
    is_recommended: 0,
    user_id: localStorage.getItem('userId') || 0 // 默认使用当前登录用户ID
  };
  pathEditDialogVisible.value = true;
}

const handlePathRemove = async (id) => {
  try {
    const result = await axiosObject.delete(`/learningPath/${id}`);
    if (result.data.code === 200) {
      ElMessage.success('删除成功')
      await findPathList();
    } else {
      ElMessage.error('删除失败: ' + (result.data.msg || '未知错误'))
    }
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error('删除失败，请重试')
  }
}

const handlePathSave = async () => {
  // 表单验证
  if (!pathFormRef.value) return
  await pathFormRef.value.validate()

  try {
    let result;
    if (currentPath.value.id) {
      // 编辑操作
      result = await axiosObject.put('/learningPath', currentPath.value);
    } else {
      // 新增操作 - 确保用户ID正确
      currentPath.value.user_id = localStorage.getItem('userId') || currentPath.value.user_id
      result = await axiosObject.post('/learningPath', currentPath.value);
    }

    if (result.data.code === 200) {
      ElMessage.success(currentPath.value.id ? '更新成功' : '新增成功')
      await findPathList();
      pathEditDialogVisible.value = false
    } else {
      ElMessage.error((currentPath.value.id ? '更新' : '新增') + '失败: ' + (result.data.msg || '未知错误'))
    }
  } catch (error) {
    console.error((currentPath.value.id ? '更新' : '新增') + "失败:", error);
    ElMessage.error((currentPath.value.id ? '更新' : '新增') + '失败，请重试')
  }
}

// 工具列表方法
const findToolList = async () => {
  const payload = {
    ...toolCondition.value,
    page: toolCurrentPage.value,
    size: toolPageSize.value
  };

  try {
    const result = await axiosObject.post('/tool/list', payload);
    if (result.data.code === 200) {
      toolTableData.value = result.data.resultData.list || [];
      toolTotal.value = result.data.resultData.total || 0;
    } else {
      ElMessage.error('获取工具列表失败: ' + (result.data.msg || '未知错误'))
    }
  } catch (error) {
    console.error("获取工具列表失败:", error);
    ElMessage.error('网络错误，无法获取工具列表')
    toolTableData.value = [];
    toolTotal.value = 0;
  }
};

// 工具分页处理
const handleToolCurrentChange = (page) => {
  toolCurrentPage.value = page;
  findToolList();
}

const handleToolSizeChange = (size) => {
  toolPageSize.value = size;
  toolCurrentPage.value = 1;
  findToolList();
}

// 工具条件查询
const searchTool = () => {
  toolCurrentPage.value = 1;
  findToolList();
}

// 重置工具查询条件
const resetToolSearch = () => {
  toolCondition.value = {"name": "", "type": "", "status": ""};
  toolCurrentPage.value = 1;
  findToolList();
}

// 工具操作方法
const handleToolView = (row) => {
  currentTool.value = {...row}
  toolViewDialogVisible.value = true
}

const handleToolEdit = (row) => {
  toolEditDialogTitle.value = "编辑工具";
  currentTool.value = {...row}
  toolEditDialogVisible.value = true
}

const handleAddTool = () => {
  toolEditDialogTitle.value = "新增工具";
  currentTool.value = {
    name: '',
    type: '',
    description: '',
    free: '1',
    price: 0,
    status: 'active',
    thumbnail_url: ''
  }
  toolEditDialogVisible.value = true
}

const handleToolRemove = async (id) => {
  try {
    const result = await axiosObject.delete(`/tool/${id}`);
    if (result.data.code === 200) {
      ElMessage.success('删除成功')
      await findToolList();
    } else {
      ElMessage.error('删除失败: ' + (result.data.msg || '未知错误'))
    }
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error('删除失败，请重试')
  }
}

const handleToolSave = async () => {
  // 表单验证
  if (!toolFormRef.value) return
  await toolFormRef.value.validate()

  try {
    let result;
    if (currentTool.value.id) {
      // 编辑操作
      result = await axiosObject.put('/tool', currentTool.value);
    } else {
      // 新增操作
      result = await axiosObject.post('/tool', currentTool.value);
    }

    if (result.data.code === 200) {
      ElMessage.success(currentTool.value.id ? '更新成功' : '新增成功')
      await findToolList();
      toolEditDialogVisible.value = false
    } else {
      ElMessage.error((currentTool.value.id ? '更新' : '新增') + '失败: ' + (result.data.msg || '未知错误'))
    }
  } catch (error) {
    console.error((currentTool.value.id ? '更新' : '新增') + "失败:", error);
    ElMessage.error((currentTool.value.id ? '更新' : '新增') + '失败，请重试')
  }
}

// 页面初始化
onMounted(async () => {
  await fetchUserInfo()
  await fetchUserStats()
  await findPathList()
  await findToolList()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.main-content {
  display: flex;
  gap: 20px;
}

.content-left {
  width: 350px;
  flex-shrink: 0;
}

.content-right {
  flex-grow: 1;
}

.profile-card {
  width: 100%;
}

.profile-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.avatar-container {
  position: relative;
  margin-bottom: 15px;
}

.avatar {
  border: 3px solid #f0f0f0;
}

.default-avatar {
  font-size: 40px;
  color: #666;
}

.avatar-upload {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.avatar-upload input {
  display: none;
}

.user-info {
  text-align: center;
  width: 100%;
  padding: 0 15px;
}

.nickname {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
}

.user-detail {
  color: #666;
  font-size: 14px;
  margin: 5px 0;
  text-align: left;
  padding-left: 20px;
}

.profile-stats {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
  padding: 10px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.card-header-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
}

.demo-form-inline .el-input,
.demo-form-inline .el-select {
  width: 200px;
}

.demo-pagination-block {
  margin-top: 15px;
  text-align: right;
}

.learning-path-card, .tools-card {
  transition: all 0.3s ease;
}

.learning-path-card:hover, .tools-card:hover {
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}
</style>